package com.rent.house.util;

import com.rent.common.exception.BusinessException;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class FileTypeUtil {
    private static final Map<String, byte[]> MAGIC = new HashMap<>();
    static {
        MAGIC.put("jpg", new byte[]{(byte) 0xFF, (byte) 0xD8});
        MAGIC.put("png", new byte[]{(byte) 0x89, 0x50, 0x4E, 0x47});
    }

    public static void assertAllow(MultipartFile file) {
        String ext = StringUtils.getFilenameExtension(file.getOriginalFilename());
        if (ext == null || !MAGIC.containsKey(ext.toLowerCase()))
            throw new BusinessException("图片格式非法");
        try (InputStream inputStream = file.getInputStream()) {
            byte[] header = new byte[8];
            int bytesRead = inputStream.read(header);
            if (bytesRead < 0) {
                throw new BusinessException("文件为空");
            }
            if (!Arrays.equals(Arrays.copyOf(header, Math.min(bytesRead, MAGIC.get(ext.toLowerCase()).length)),
                    Arrays.copyOf(MAGIC.get(ext.toLowerCase()), Math.min(bytesRead, MAGIC.get(ext.toLowerCase()).length))))
                throw new BusinessException("文件头与扩展名不符");
        } catch (IOException e) {
            throw new BusinessException("读取文件失败");
        }
    }
}
